package com.blb.action;

import java.util.List;
import java.util.Set;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
import org.hibernate.query.Query;

import com.blb.entity.Menu;
import com.blb.entity.Role;
import com.blb.entity.User;
import com.blb.utils.HibernateUtil;
import com.opensymphony.xwork2.ActionSupport;

public class TestAction extends ActionSupport {

	private List<User> listUser;
	
	
	public List<User> getListUser() {
		return listUser;
	}

	public void setListUser(List<User> listUser) {
		this.listUser = listUser;
	}

	/**
	 * 查询user
	 * @return
	 */
	public String User(){
		Session session = HibernateUtil.getSession();
		Transaction transaction = session.beginTransaction();
		
		
		Query queryUser = session.createQuery("from User");
		listUser = queryUser.list();
		for(User user :listUser){
			System.out.println(user);
		}
		
		transaction.commit();
		
		HibernateUtil.close();
		return "user";
	}
	
	/**
	 * 查询role
	 * @return
	 */
	public String Role(){
		Session session = HibernateUtil.getSession();
		Transaction transaction = session.beginTransaction();
		
		Query queryRole = session.createQuery("from Role");
		List<Role> listRole = queryRole.list();
		for(Role role :listRole){
			System.out.println(role);
		}
		
		
		HibernateUtil.close();
		return SUCCESS;
	}
	
	/**
	 * 查询menu
	 * @return
	 */
	public String Menu(){
		Session session = HibernateUtil.getSession();
		Transaction transaction = session.beginTransaction();
		
		Query queryMenu = session.createQuery("from Menu");
		List<Menu> listMenu = queryMenu.list();
		for(Menu menu :listMenu){
			System.out.println(menu);
		}
		
		HibernateUtil.close();
		return SUCCESS;
	}
	
	/**
	 * 添加角色
	 * @return
	 */
	public String insert(){
		Session session = HibernateUtil.getSession();
		Transaction transaction = session.beginTransaction();
		Role role = new Role();
		role.setRolename("程序员");
		role.setNote("11111111");
		session.save(role);
		transaction.commit();
		HibernateUtil.close();
		return SUCCESS;
	}
	
	/**
	 * 删除用户
	 * @return
	 */
	public String deleteUser(){
		Session session = HibernateUtil.getSession();
		Transaction transaction = session.beginTransaction();
		
		
		User user = session.get(User.class, "7958a8cfeecd48ea95f327b8052ed33d");
		Set<Role> role = user.getRole();
		role.clear();
		session.delete(user);
		
		transaction.commit();
		HibernateUtil.close();
		return SUCCESS;
	}
}
